<template>
  <div>
    <van-nav-bar title="登录"/>
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
        required
      />
      <van-field
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
        required
      />
      <div style="margin: 16px;">
        <van-button
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="登录中..."
          round
          block
          type="info"
          native-type="submit"
        >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
// import { setToken } from '@/utils/storage'
export default {
  name: 'Login',
  data () {
    return {
      mobile: '13912345678',
      code: '246810',
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'onBlur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'onBlur' }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'onBlur' },
          { pattern: /^\d{6}$/, message: '验证码格式错误', trigger: 'onBlur' }
        ]
      },
      isLoading: false
    }
  },
  methods: {
    async onSubmit () {
      this.isLoading = true
      // 表单校验通过了才会触发submit事件
      // 发送ajax请求
      try {
        const res = await login(this.mobile, this.code)
        console.log(res)
        this.$toast.success('登录成功')
        // 存储token
        // setToken(res.data.data)
        // 把token存储到vuex中
        this.$store.commit('setToken', res.data)
        const back = this.$route.query.back || '/'
        // console.log(back)
        this.$router.push(back)
      } catch (err) {
        console.log(err)
        this.$toast.fail('登录失败')
      }
      this.isLoading = false
    }
  }
}
</script>

<style>

</style>
